package Stragos.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import Stragos.excepcion.DAOExcepcion;
import Stragos.modelo.Boleta;
import Stragos.modelo.Comprobante;
import Stragos.modelo.DetalleComprobante;
import Stragos.modelo.Factura;
import Stragos.util.ConexionBD;



public class ComprobanteDAO extends BaseDAO {

	public Comprobante insertar(Comprobante vo) throws DAOExcepcion {
		
		System.out.println("ComprobanteDAO: insertar()");
		String query = "INSERT INTO comprobante (idcomprobante, fecha, monto, idcajero) VALUES (?,?,?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;

		try {
			con = ConexionBD.obtenerConexion();
			con.setAutoCommit(false);
			stmt = con.prepareStatement(query);
			stmt.setInt(1, vo.getIdComprobante());
			stmt.setDate(2, vo.getFecha());
			stmt.setDouble(3, vo.getMonto());
			stmt.setInt(4, vo.getIdCajero());

			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar");
			}

			int idc = 0;
			query = "SELECT LAST_INSERT_ID()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				idc = rs.getInt(1);
			}
			vo.setIdComprobante(idc);
			
			if(vo instanceof Factura ) {
				query = "INSERT INTO factura (numerofactura, ruc, idcomprobante) VALUES (?,?,?)";	
				stmt = con.prepareStatement(query);
				stmt.setString(1, ((Factura) vo).getNumeroFactura());
				stmt.setString(2, ((Factura) vo).getRuc());
				stmt.setInt(3, vo.getIdComprobante());				
			}else if(vo instanceof Boleta) {
				query = "INSERT INTO boleta (numeroboleta, idcomprobante) VALUES (?,?)";
				stmt = con.prepareStatement(query);
				stmt.setString(1, ((Boleta) vo).getNumeroBoleta());
				stmt.setInt(2, vo.getIdComprobante());				
			}
			
			rs = stmt.executeQuery();
			
			for (DetalleComprobante com : vo.getDetalles()) {
				query = "INSERT INTO detallecomprobante(idcomprobante, idproducto, cantidad) VALUES (?,?,?)";
				stmt = con.prepareStatement(query);
				stmt.setInt(1, idc);
				stmt.setInt(2, com.getProducto().getIdProducto());
				stmt.setInt(3, com.getCantidad());
				int u = stmt.executeUpdate();
				if (u != 1) {
					throw new SQLException("No se pudo insertar");
				}
			}
			con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				throw new DAOExcepcion(e.getMessage());
			}
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			try {
				con.setAutoCommit(true);
			} catch (SQLException e) {
				throw new DAOExcepcion(e.getMessage());
			}
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}

}